<template>
    <div class="organization-type-management">
        <pageTitle :title="'組織類型管理'" />

        <!-- 頂部操作欄 -->
        <div class="top-action-bar">
            <el-row :gutter="20" align="middle">
                <el-col :span="12">
                    <el-input v-model="searchQuery" placeholder="請輸入組織類型名稱" clearable @clear="handleSearch"
                        @keyup.enter="handleSearch">
                        <template #append>
                            <el-button type="primary" @click="handleSearch">
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="12" class="action-buttons">
                    <el-button type="primary" @click="addOrganizationType">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>新增組織類型</span>
                    </el-button>
                    <el-button type="danger" @click="batchDelete" :disabled="selectedTypes.length === 0">
                        <el-icon>
                            <Delete />
                        </el-icon>
                        <span>批量刪除</span>
                    </el-button>
                    <el-button type="success" @click="saveSortOrder" :disabled="!sortChanged" :loading="savingOrder">
                        <el-icon>
                            <Check />
                        </el-icon>
                        <span>保存排序</span>
                    </el-button>
                </el-col>
            </el-row>
        </div>

        <!-- 組織類型表格 -->
        <div class="organization-type-table">
            <el-table :data="filteredOrganizationTypes" style="width: 100%" v-loading="loading" row-key="id"
                @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="排序" width="80" align="center">
                    <template #default="{ }">
                        <el-icon class="drag-handle" :size="16">
                            <Rank />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="組織類型名稱" width="180" />
                <el-table-column prop="description" label="描述" width="300" show-overflow-tooltip />
                <el-table-column label="狀態" width="200" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.isActive" active-text="啟用" inactive-text="停用"
                            @change="toggleStatus(row)" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editOrganizationType(row)">
                            編輯
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteOrganizationType(row)">
                            刪除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增/編輯組織類型對話框 -->
        <el-dialog v-model="dialogVisible" :title="isEditMode ? '編輯組織類型' : '新增組織類型'" width="500px">
            <el-form :model="organizationTypeForm" :rules="formRules" ref="formRef" label-width="120px">
                <el-form-item label="組織類型名稱" prop="name">
                    <el-input v-model="organizationTypeForm.name" placeholder="請輸入組織類型名稱" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="organizationTypeForm.description" type="textarea" :rows="3"
                        placeholder="請輸入描述" />
                </el-form-item>
                <el-form-item label="狀態">
                    <el-switch v-model="organizationTypeForm.isActive" active-text="啟用" inactive-text="停用" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">確定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete, Check, Rank } from '@element-plus/icons-vue'
import Sortable from 'sortablejs'
import pageTitle from "@/components/pageTitle/pageTitle.vue"

// 定義表單 ref
const formRef = ref(null)

// 響應式數據
const searchQuery = ref('')
const loading = ref(false)
const dialogVisible = ref(false)
const isEditMode = ref(false)
const selectedTypes = ref([])
const savingOrder = ref(false)
const sortChanged = ref(false)
const originalOrder = ref([])

// 組織類型數據
const organizationTypes = ref([
    { id: 1, name: '總公司', description: '集團總部', isActive: true, sortOrder: 1 },
    { id: 2, name: '分公司', description: '地區分公司', isActive: true, sortOrder: 2 },
    { id: 3, name: '子公司', description: '控股子公司', isActive: true, sortOrder: 3 },
    { id: 4, name: '辦事處', description: '地區辦事處', isActive: false, sortOrder: 4 },
    { id: 5, name: '事業部', description: '業務事業部', isActive: true, sortOrder: 5 },
])

// 表單數據
const organizationTypeForm = reactive({
    id: null,
    name: '',
    description: '',
    isActive: true,
    sortOrder: 0
})

// 表單驗證規則
const formRules = {
    name: [
        { required: true, message: '請輸入組織類型名稱', trigger: 'blur' },
        { min: 2, max: 20, message: '長度在 2 到 20 個字符', trigger: 'blur' }
    ]
}

// 過濾後的組織類型
const filteredOrganizationTypes = computed(() => {
    return organizationTypes.value
        .filter(item =>
            item.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
            item.description.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
        .sort((a, b) => a.sortOrder - b.sortOrder)
})

// 生命週期鉤子
onMounted(() => {
    fetchOrganizationTypes()
    initSortable()
})

// 方法
const fetchOrganizationTypes = () => {
    loading.value = true
    // 模擬API請求
    setTimeout(() => {
        originalOrder.value = [...organizationTypes.value]
        loading.value = false
    }, 500)
}

const handleSearch = () => {
    // 搜索功能
}

const handleSelectionChange = (selection) => {
    selectedTypes.value = selection
}

const addOrganizationType = () => {
    isEditMode.value = false
    resetForm()
    dialogVisible.value = true
}

const editOrganizationType = (row) => {
    isEditMode.value = true
    Object.assign(organizationTypeForm, row)
    dialogVisible.value = true
}

const deleteOrganizationType = (row) => {
    ElMessageBox.confirm(`確定要刪除組織類型「${row.name}」嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        organizationTypes.value = organizationTypes.value.filter(item => item.id !== row.id)
        ElMessage.success('刪除成功')
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const batchDelete = () => {
    if (selectedTypes.value.length === 0) {
        ElMessage.warning('請至少選擇一個組織類型')
        return
    }

    ElMessageBox.confirm(`確定要刪除選中的 ${selectedTypes.value.length} 個組織類型嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const selectedIds = selectedTypes.value.map(item => item.id)
        organizationTypes.value = organizationTypes.value.filter(item => !selectedIds.includes(item.id))
        selectedTypes.value = []
        ElMessage.success(`已成功刪除 ${selectedIds.length} 個組織類型`)
    }).catch(() => {
        ElMessage.info('已取消批量刪除')
    })
}

const toggleStatus = (row) => {
    const message = row.isActive ? '已啟用' : '已停用'
    ElMessage.success(`組織類型「${row.name}」${message}`)
}

const resetForm = () => {
    organizationTypeForm.id = null
    organizationTypeForm.name = ''
    organizationTypeForm.description = ''
    organizationTypeForm.isActive = true
    organizationTypeForm.sortOrder = organizationTypes.value.length + 1
}

const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (isEditMode.value) {
                // 更新組織類型
                const index = organizationTypes.value.findIndex(item => item.id === organizationTypeForm.id)
                if (index !== -1) {
                    organizationTypes.value[index] = { ...organizationTypeForm }
                }
                ElMessage.success('更新成功')
            } else {
                // 新增組織類型
                const newId = Math.max(...organizationTypes.value.map(item => item.id), 0) + 1
                organizationTypes.value.push({
                    ...organizationTypeForm,
                    id: newId,
                    sortOrder: organizationTypes.value.length + 1
                })
                ElMessage.success('新增成功')
            }
            dialogVisible.value = false
        }
    })
}

// 拖拽排序相關
const initSortable = () => {
    const table = document.querySelector('.organization-type-table .el-table__body-wrapper tbody')

    Sortable.create(table, {
        animation: 150,
        handle: '.drag-handle',
        onEnd: ({ newIndex, oldIndex }) => {
            if (newIndex !== oldIndex) {
                const movedItem = organizationTypes.value.splice(oldIndex, 1)[0]
                organizationTypes.value.splice(newIndex, 0, movedItem)

                // 更新排序序號
                organizationTypes.value.forEach((item, index) => {
                    item.sortOrder = index + 1
                })

                sortChanged.value = true
            }
        }
    })
}

const saveSortOrder = () => {
    savingOrder.value = true
    // 模擬API請求
    setTimeout(() => {
        ElMessage.success('排序已保存')
        sortChanged.value = false
        savingOrder.value = false
        originalOrder.value = [...organizationTypes.value]
    }, 800)
}

const tableRowClassName = ({ row }) => {
    return !row.isActive ? 'inactive-row' : ''
}
</script>

<style scoped lang="less">
.organization-type-management {
    padding: 20px;
    background-color: #fff;

    .top-action-bar {
        margin-bottom: 20px;
        padding: 16px 24px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        margin-top: 20px;

        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
        }
    }

    .organization-type-table {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        background-color: #fff;

        :deep(.el-table__body-wrapper) {
            tbody {
                .drag-handle {
                    cursor: move;
                    color: var(--el-color-primary);
                }

                .inactive-row {
                    opacity: 0.6;
                    color: var(--el-text-color-secondary);
                }
            }
        }
    }
}
</style>